package com.lqk.channel.filechannel;

import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * FileChannel 写操作
 */
public class FileChannelDemo2 {

    public static void main(String[] args) throws Exception {
        // 打开 FileChannel
        RandomAccessFile accessFile = new RandomAccessFile("f:\\lqk\\001.txt","rw");
        FileChannel channel = accessFile.getChannel();

        // 创建 buffer 对象
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        String newData="data lqk";
        buffer.clear();

        // 写入数据
        buffer.put(newData.getBytes());
        buffer.flip();//模式转换

        // FileChannel 完成最终实现
        while (buffer.hasRemaining()){
            channel.write(buffer);
        }
        // 关闭 channel
        channel.close();
    }
}
